<?php
/**
 * Created by allen.qiang 20170713.
 * User: Administrator
 * Date: 2017/7/13
 * Time: 15:04
 * redis操作类，用于用户登录信息，后期订单 ，以及需要存入REDIS的缓存数据。
 */

namespace common\helps;
use common\models\CustMaster;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

class redisHelper{
    //redis中前端用户登录KEY前缀 add by allen.qiang 20170909
    private $cust_login_prefix = 'cust_login_';

	//add by FDG367 20180111 437 注册完毕直接是为登录状态，微信跳转key  start loginReferrer
    private static $cust_wechat_redirect = 'cust_wechat_redirect_uri_';
    //导航前缀
    private $web_nav_prefix = 'jd_mall_web_nav_';
	//redis线下会员KEY前缀 add by FDG367
    private static  $cust_genre_merber_  = 'cust_genre_member_';
    private static  $cust_mobile_merber  = 'cust_mobile_member_';
	//del by allen.qiang 20180126 删除无用代码 start
    //private static  $wechat_token  	= 'wechat_token';
	//del by allen.qiang 20180126 删除无用代码 end
	private static  $wechat_ticket  = 'wechat_ticket';
	const WECHAT_EXPIRE_CUT		=  200;			//微信token有效时间减去200秒

    /**
     * 取得当前SESSION_ID
     */
	//mod by FDG367 缓存方法定义错误 453 start
    //private function getSessionID(){
    private static function getSessionID(){
	//mod by FDG367 缓存方法定义错误 453 end
        if(!isset($_SESSION)){
            session_start();
        }
        return session_id();
    }

    /**
     * @param $key
     * @return string
     * 拼接本项目REDIS前缀
     */
    private function getKey($key){
        return Yii::$app->params['sys_redis_prefix'] . $key;
    }
    /**
     * @param $userInfo
     * 保存登录信息到REDIS中
     */
    public function setLoginInfo($userInfo){
        $source = Yii::$app->redis->setex($this->getKey('login_'.session_id()),Yii::$app->params['backend_session_timeout'],json_encode($userInfo));
        if(!$source){
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('ERROR-->保存用户信息到redis 出错！');
			error_log('error->' . __METHOD__ . 'error: 保存用户信息到redis 出错！ ');
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
        }
    }

    /**
     * @return bool
     * 判断当前客户端是否已登录状态
     */
    public function isloggedin(){
        $source = Yii::$app->redis->get($this->getKey('login_'.self::getSessionID()));
        if(!$source){
            return false;
        }
        return true;
    }

    /**
     * @return mixed
     * 取得已登录用户信息
     */
    public function getloginUserInfo(){
        $result =  Yii::$app->redis->get($this->getKey('login_'.self::getSessionID()));
        if($result)
            return json_decode($result);
        else
            return null;
    }

    /**
     * 退出登录
     */
    public function logOut(){
        $source = Yii::$app->redis->del($this->getKey('login_'.self::getSessionID()));
    }

    /**
     * 延续会话时效
     */
    public function resetSessionTime(){
        Yii::$app->redis->expire($this->getKey('login_'.self::getSessionID()),Yii::$app->params['backend_session_timeout']);
    }

    /**
     * @param
     * 保存手机验证码信息到REDIS中
     */
    public function setSmsCode($mobile,$code){
        $source = Yii::$app->redis->setex($this->getKey('sms_code'.$mobile),Yii::$app->params['sms_code_timeout'],$code);
        if(!$source){
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('ERROR-->保存用户信息到redis 出错！');
			error_log('error->' . __METHOD__ . 'error: 保存用户信息到redis 出错！ ');
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
        }
    }

    /**
     * @param
     * 获取手机验证码信息
     */
    public function getSmsCode($mobile){
        $result = Yii::$app->redis->get($this->getKey('sms_code'.$mobile));
        if($result)
            return json_decode($result);
        else
            return null;
    }

    /**
     * @param $masterInfo
     * 保存登录信息到REDIS中
     */
    public function setMasterInfo($masterInfo){
        $source = Yii::$app->redis->setex($this->getKey($this->cust_login_prefix .self::getSessionID()),Yii::$app->params['frontend_session_timeout'],json_encode($masterInfo));
        if(!$source){
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('ERROR-->保存Master信息到redis 出错！');
			error_log('error->' . __METHOD__ . 'error: 保存Master信息到redis 出错！ ');
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
        }
    }

	/**
	 * @param add by FDG367 登录后，登录状态为24小时的有效期 454 20180117 start
	 * @param return null
	 */
	public static function extendSessionTime(){
		Yii::$app->redis->expire((new static())->getKey((new static())->cust_login_prefix .self::getSessionID()),Yii::$app->params['frontend_session_timeout']);
	}
	//add by FDG367 登录后，登录状态为24小时的有效期 454 20180117 end

	/**
     * @return bool
     * 判断当前客户端是否已登录状态
     */
    public function isLogin(){
        $source = Yii::$app->redis->get($this->getKey($this->cust_login_prefix .self::getSessionID()));
        if(!$source){
            return false;
        }
        return true;
    }

    /**
     * @return mixed
     * 取得已登录用户信息
     */
    public function getLoginMasterInfo(){
        $result =  Yii::$app->redis->get($this->getKey($this->cust_login_prefix.self::getSessionID()));
        if($result)
            return json_decode($result);
        else
            return null;
    }

    /**
     * 退出登录
     */
    public function masterLogOut(){
        $source = Yii::$app->redis->del($this->getKey($this->cust_login_prefix.self::getSessionID()));
    }

	/**
	 * @param  设置线下会员或手机号的关系
	 * @param $memberNo线下会员号
	 * @param $mobile线下会员号
	 * @return string
	 */
	public static function setMasterRelateGenerMerber($memberNo,$mobile){
		return  Yii::$app->redis->set((new static())->getKey(self::$cust_genre_merber_.$memberNo,$mobile));
	}

	/**
	 * @param  通过线下会员查找会员线上会员手机号
	 * @param $memberNo线下会员号
	 * @return string
	 */
	public static  function getMasterRelateGenerMerber($memberNo){
		$result	= Yii::$app->redis->get((new static())->getKey(self::$cust_genre_merber_.$memberNo));
		if(!$result){
			//根据$memberNo查询当前手机号
			if(!$maserterUserInfo	= CustMaster::getMastertMobile($memberNo))
				return null;

			self::setMasterRelateGenerMerber($memberNo,$maserterUserInfo->mobile);

			return $maserterUserInfo->mobile;
		}
		return $result;
	}

	/**
	 * @param  删除线下会员或手机号的对应关系
	 */
	public static function delMasterRelateGenerMerber($memberNo){
		if (Yii::$app->redis->exists((new static())->getKey(self::$cust_genre_merber_. $memberNo))) {
			if (!Yii::$app->redis->del((new static())->getKey(self::$cust_genre_merber_. $memberNo))) {
				return false;
			}
		}
		return true;

	}

	/**
	 * @prarm 跟手机号存储用户信息
	 */
	public static function setMastserMobileInfo($mobile,$data){

		return Yii::$app->redis->set((new static())->getKey(self::$cust_mobile_merber.$mobile),json_encode($data));
	}

	/**
	 * @param $mobile 通过手机号获取用户的信息
	 * @return array|bool|mixed
	 */
	public static function getMastserMobileInfo($mobile){

		$result	= Yii::$app->redis->get((new static())->getKey(self::$cust_mobile_merber.$mobile));

		if(!$result){

			//获取用户的基本信息
			$custMasterInfo	=CustMaster::getMastertMobileInfo($mobile);
			//如果为空返回false
			if(empty($custMasterInfo)){
				return false;
			}

			$custInfo	= ArrayHelper::toArray($custMasterInfo);

			self::setMastserMobileInfo($mobile,$custInfo);
			return $custInfo;
		}
		return json_decode($result);
	}

	/**
	 * @prarm 删除手机号存储用户信息
	 */
	public static function delMastserMobileInfo($mobile)
	{

		if (Yii::$app->redis->exists((new static())->getKey(self::$cust_mobile_merber . $mobile))) {

			if (!Yii::$app->redis->del((new static())->getKey(self::$cust_mobile_merber . $mobile))) {
				return false;
			}
		}

		return true;

	}


	/**
	 * @param 判断当前微信登录是否绑定手机
	 * @return bool
	 */
	public function isWeChatRelationMobile(){
		//$source = json_decode(Yii::$app->redis->get($this->getKey($this->cust_login_prefix .self::getSessionID())));
		$source	= tools::getloginMasterInfo();
		//存在手机号则判断为手机登录
		if(isset($source->mobile)&& $source->mobile){
			return true;
		}
		
		return false;
	}

    /**
     * 缓存导航信息
     * @param $nav array
     */
    public function setFrontendNavMenu($nav){
        $source = Yii::$app->redis->setex($this->getKey($this->web_nav_prefix),Yii::$app->params['frontend_nav_session_timeout'],json_encode($nav,JSON_UNESCAPED_UNICODE));
        if(!$source){
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('error->缓存导航信息到redis 出错！');
			error_log('error->' . __METHOD__ . 'error: 缓存导航信息到redis 出错！ ');
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
        }
    }

    /**
     * 获取导航信息
     * @return mixed|null
     */
    public function getFrontendNavMenu(){
        $result =  Yii::$app->redis->get($this->getKey($this->web_nav_prefix));
        if(!empty($result)){
            return json_decode($result,true);
        }else{
            return array();
        }
    }

    /**
     * 清除导航缓存信息
     */
    public function delFrontendNavMenu(){
        $source = Yii::$app->redis->del($this->getKey($this->web_nav_prefix));
    }

	/**
	 * 获取微信token
	 * @return mixed|object
	 */
	public static function getWechatToken(){

		return Wechat::getWechatToken();
		/*$wechatTokenInfo	= json_decode(Yii::$app->redis->get((new static())->getKey(self::$wechat_token)));
		$selfModel	= new static();
		try{

			if(!isset($wechatTokenInfo->access_token) || !$wechatTokenInfo->access_token){

				if(!$wechatTokenInfo = Wechat::getWechatToken()){
					throw new \Exception('获取微信token失败');
				}

				Yii::$app->redis->set($selfModel->getKey(self::$wechat_token),json_encode($wechatTokenInfo));
				Yii::$app->redis->expire($selfModel->getKey(self::$wechat_token),$wechatTokenInfo->expires_in-$selfModel::WECHAT_EXPIRE_CUT);
			}

			return $wechatTokenInfo;
		}catch (\Exception $e){
			Yii::trace('微信token写入redis失败');
			return $e->getMessage();
		}*/

	}

	/**
	 * @param huoqu
	 */
	public static function getJsApiTicket(){
		$wechatJsApiTicket	= json_decode(Yii::$app->redis->get((new static())->getKey(self::$wechat_ticket)));

		$selfModel	= new static();
		try{

			if(!isset($wechatJsApiTicket->ticket) || !$wechatJsApiTicket->ticket){

				if(!$wechatJsApiTicket = Wechat::getJsApiTicket()){
					//mod by allen.qiang 20180126 异常处理，日志优化 442  start
					//error_log('error->获取微信token失败');
					error_log('error->' . __METHOD__ . 'error: 获取微信token失败');
					//mod by allen.qiang 20180126 异常处理，日志优化 442    end
					throw new \Exception('获取微信token失败');
				}

				Yii::$app->redis->set($selfModel->getKey(self::$wechat_ticket),json_encode($wechatJsApiTicket));
				Yii::$app->redis->expire($selfModel->getKey(self::$wechat_ticket),$wechatJsApiTicket->expires_in-$selfModel::WECHAT_EXPIRE_CUT);
			}

			return $wechatJsApiTicket;
		}catch (\Exception $e){
			Yii::trace('微信token写入redis失败');
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('error->微信token写入redis失败');
			error_log('error->' . __METHOD__ . 'error: 微信token写入redis失败 ' . $e->getMessage());
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
			return $e->getMessage();
		}

	}
	public static function addUserID(){
		return CustMaster::find()->select(['id'])->where(['use_flg'=>CustMaster::USER_FLAG_YES])->all();
	}

	public static  function popData(){
		return Yii::$app->redis->lpop('ceshi');
	}

	/**
	 * @param add by FDG367 20180111 437 注册完毕直接是为登录状态，跳转至注册前一页  start loginReferrer
	 * @param 记录微信登录缓存
	 */
	public static function setWeChatRedirectUri($url=''){
		$source = Yii::$app->redis->setex((new static())->getKey(self::$cust_wechat_redirect.self::getSessionID()),Yii::$app->params['frontend_wechat_redirect_uri'],$url);
		if(!$source){
			//mod by allen.qiang 20180126 异常处理，日志优化 442  start
			//error_log('ERROR-->保存Master信息到redis 出错！');
			error_log('error->' . __METHOD__ . 'error: 保存Master信息到redis 出错！');
			//mod by allen.qiang 20180126 异常处理，日志优化 442    end
		}
	}

	/**
	 * @param add by FDG367 20180111 437 注册完毕直接是为登录状态，跳转至注册前一页  start loginReferrer
	 * @param 获取微信登录缓存
	 */
	public static function getWeChatRedirectUri(){
		$result =  Yii::$app->redis->get((new static())->getKey(self::$cust_wechat_redirect.self::getSessionID()));
		if($result)
			return $result;
		else
			return null;
	}


	/**
	 * @param add by FDG367 20180111 437 注册完毕直接是为登录状态，跳转至注册前一页  start loginReferrer
	 * @param 删除缓存
	 */
	public static function delWeChatRedirectUri(){
		Yii::$app->redis->del((new static())->getKey(self::$cust_wechat_redirect.self::getSessionID()));
	}

}